<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 2016/9/28
 * Time: 23:58
 */

namespace Home\Controller;


use Common\Utils\WeChatUtils;

use Home\Logic\UserLogic;
use Think\Controller;
use Think\Log;

class WeChatController extends Controller
{
    private $_utils;
    public function __construct()
    {
        parent::__construct();
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $this->_utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
    }
    public function firstVaild()
    {
        //检验签名的合法性
        if ($this->_checkSignature()) {
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
        }
    }
    /**
     * 验证签名
     * @return bool
     */
    private function _checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'gouhuiwan';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
    //网页授权回调
    public function html_return(){
        $file = 'log';
        $fp = fopen($file, 'a+');
        flock($fp, LOCK_EX);
        $code = I('code');
        $state = I('state');
        if('' != $state && strstr($state,"#")) {
            $state = explode('#',$state);
            $state = $state[0];
        }
        $state = explode('_',$state);
        $user_id = $state[0];
        $url = $state[1];
        $result = $this->_utils->getHtmlAccessToken($code);
        if(!$result){
            flock($fp, LOCK_UN);
            fclose($fp);
//            var_dump('getHtmlAccessToken');
            return;
        }
        session('openid',$result->openid);//存入sessoin
        $model = D('Users');
        $user = $model->where(array('openid'=>':openid'))->bind(array(':openid'=>$result->openid))->find();
        //获取用户详细信息
        $userInfo = $this->_utils->getUserInfo($result->access_token,$result->openid);
        if(!$user){
            $logic = new UserLogic();
            $user = $logic->bindSuperior($userInfo->openid,$user_id);
            $user = $this->makeuser($userInfo,$user);
            $model->save($user);
        }else{

            $user = $this->makeUser($userInfo,$user);
            $model->save($user);
            $user = D('Users')->where(array('user_id'=>$user['user_id']))->find();
        }
        session('user',$user);//存入sessoin
        flock($fp, LOCK_UN);
        fclose($fp);
        if(empty($url)) {
            $this->redirect('/Home/Index/index');
        }else if($url == 'QRCode'){
            $this->redirect('/Home/Me/goToQRCode');
        }else if($url == 'Order'){
            $this->redirect('/Home/Order/index');
        }else if($url == 'Problem'){
            $this->redirect('/Home/Me/problem');
        }
    }


    private function makeUser($userInfo,$user){
        $user['nickname'] =  match_chinese($userInfo->nickname);
        $user['head_pic'] = $userInfo->headimgurl;
        return $user;
    }

    /**
     * 跳转到我的二维码界面
     */
    public function goToQRCode(){
        $user_id = I('user_id');
        if(!empty($user_id)) {
            $this->assign('user_id', $user_id);
        }else{
            $user = session('user');
            $this->assign('user_id', $user['user_id']);
        }
        $this->jsSDK();
        $this->display('Me/qrcode');
    }

    /**
     * ajax 获取用户二维码
     */
    public function qrCode(){
        $user_id = I('user_id');
        if(empty($user_id)){
            $user = session('user');
            $user_id = $user['user_id'];
        }
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $utils->getQRCode($user_id);
    }

    /**网页授权
     * @param $user_id=null 用户id
     * @param $url=null 跳转的URL
     */
    public function login($user_id=null,$url=null){
        if(empty($user_id)){
            $user_id = '1';
        }
        if(!empty($url)) {
            $user_id .= '_' . $url;
        }
        $this->_utils->getUserCode($user_id);
    }


    protected function jsSDK(){
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $ticket = $utils->getJsApiTicket();
        $noncestr = $utils->getRandCode();//获取随机码
        $timestamp = time();//时间戳
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//        $url = U('Home/WeChat/invite/'.$user['id']);
        $str = 'jsapi_ticket=' . $ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url='.$url;
        $signature = sha1($str);
        $this->assign('host',"$protocol$_SERVER[HTTP_HOST]");
        $this->assign('appId',$APPID);
        $this->assign('ticket',$ticket);
        $this->assign('noncestr',$noncestr);
        $this->assign('timestamp',$timestamp);
        $this->assign('signature',$signature);
        $this->assign('BASE_URL',C('BASE_URL'));//域名
    }

}